// store命名
import { StoreName } from '@store/store-name';
// api
import { getRoutes } from '@api/user';
/* Layout */
import Layout from '@/layout/index.vue';
// 路由
import router from '@/router';
import { RouteRecordRaw } from 'vue-router';
import { useSystemStore } from './system';

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue');

// 用户模块
export const usePermissionStore = defineStore(StoreName.PERMISSION, {
    state: (): Permission => ({
        routes: [],
        sidebarRouters: [],
    }),
    actions: {
        // 获取路由
        generateRoutes(): Promise<any> {
            return new Promise((resolve, _reject): any => {
                getRoutes().then((res) => {
                    const DR = generateDynamicRoutes(res.data);
                    this.sidebarRouters = DR;
                    DR.forEach((R: RouteRecordRaw) => {
                        router.addRoute(R);
                    });
                    resolve(DR);
                });
            });
        },
        // 清除路由
        clearRoute() {
            this.sidebarRouters = [];
            this.routes = [];
        },
        // 添加路由
        addRoutes(routes: any[]) {
            this.sidebarRouters = [...this.sidebarRouters, routes];
        },
        // 删除路由
        removeRoutes(routeName: string) {
            this.sidebarRouters = this.sidebarRouters.filter((item) => item.name !== routeName);
        },
    },
    persist: {
        storage: sessionStorage,
    },
});

// 生成路由
function generateDynamicRoutes(data: any) {
    const dynamicroutes: any = [];
    // 循环对象
    for (const key in data) {
        // 生成父元素
        const parentRoute = generateParentRoute(key);
        // 生成子元素
        const childRoutes = generateChildRoutes(data[key]);
        // 添加子元素
        parentRoute.children = childRoutes;
        // 添加父元素
        dynamicroutes.push(parentRoute);
    }
    // 添加工具路由 -- 所有用户可以访问
    // 是否显示工具路由
    if (useSystemStore().config.isShowTools) {
        dynamicroutes.push(generateToolsRoutes());
    }
    return dynamicroutes;
}
// 生成父元素
function generateParentRoute(key: string) {
    let title = '';
    let icon = '';
    switch (key) {
        case 'customer':
            title = '客户管理';
            icon = '#icon-kehuguanli';
            break;
        case 'order':
            title = '订单管理';
            icon = '#icon-dingdanguanli';
            break;
        case 'product':
            title = '产品管理';
            icon = '#icon-chanpinguanli';
            break;
        case 'supplier':
            title = '供应商管理';
            icon = '#icon-gongyingshangguanli';
            break;
        case 'production':
            title = '生产管理';
            icon = '#icon-shengchanguanli';
            break;
        case 'warehouse':
            title = '仓库管理';
            icon = '#icon-cangkuguanli';
            break;
        case 'file':
            title = '文件管理';
            icon = '#icon-wenjianguanli';
            break;
        case 'system':
            title = '系统管理';
            icon = '#icon-xitongguanli';
            break;
        default:
            break;
    }
    return {
        path: '/' + key,
        component: Layout,
        name: key,
        icon: icon,
        title: title,
        children: [],
    };
}
// 生成子元素
function generateChildRoutes(data: any) {
    // 没有三层路由，不需要递归
    const routes: any = [];
    let _path = '';
    for (const key in data) {
        // 生成路径
        for (const path in modules) {
            const dir = path.split('views')[1].split('/index.vue')[0];
            if (dir === data[key]['path']) {
                // @ts-ignore
                _path = () => modules[path]();
            }
        }
        // 生成子元素
        data[key]['component'] = _path;
        // 添加子元素
        routes.push(data[key]);
    }
    return routes;
}

// 生成工具路由
function generateToolsRoutes() {
    return {
        path: '/tools',
        component: Layout,
        name: 'tools',
        icon: '#icon-gongju',
        title: '系统工具',
        children: [
            {
                path: '/tools/processData',
                name: 'ToolsProcessData',
                meta: {
                    title: '处理数据',
                    activeMenu: '/tools/processData',
                    icon: '#icon-chulishuju',
                },
                component: () => import('@/views/tools/processData/index.vue'),
            },
        ],
    };
}
